package org.btik.light.server.dev.sensitive;

import org.btik.context.thread.SystemControlAble;
import org.btik.light.server.platform.common.timeout.TimeoutBean;
import org.btik.light.tool.DhUtil;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lustre
 * @since 2023/6/7 14:21
 */
@Component
public class DhKeyExchangeSessionManager extends Thread implements SystemControlAble {
    private volatile boolean runFlag = true;

    private final ConcurrentHashMap<String, TimeoutBean<DhUtil.DhKeyPair>> dhPublicKeyMap;

    private final byte[] lock = new byte[0];

    public DhKeyExchangeSessionManager() {
        super("DhKeyExchangeTicker");
        setPriority(3);
        dhPublicKeyMap = new ConcurrentHashMap<>();
    }

    public DhUtil.DhKeyPair getPkBySessionId(String sessionId) {
        TimeoutBean<DhUtil.DhKeyPair> dhPublicKeyTimeoutBean = dhPublicKeyMap.get(sessionId);
        return dhPublicKeyTimeoutBean == null ? null : dhPublicKeyTimeoutBean.tagert();
    }

    public void savePk(String sessionId, DhUtil.DhKeyPair dhKeyPair) {
        dhPublicKeyMap.put(sessionId, new TimeoutBean<>(dhKeyPair
                , System.currentTimeMillis(), 5 * 1000 * 60));
    }

    public void sessionOver(String sessionId){
        dhPublicKeyMap.remove(sessionId);
    }

    @Override
    public void run() {
        while (runFlag) {
            synchronized (lock) {
                try {
                    lock.wait(5 * 1000 * 60);
                } catch (InterruptedException e) {
                    if (!runFlag) {
                        break;
                    }
                }
            }
            dhPublicKeyMap.forEach((sessionId, timeoutPk) -> {
                long now = System.currentTimeMillis();
                long time = timeoutPk.lastActiveTime();
                if ((time - now) > timeoutPk.timeout()) {
                    dhPublicKeyMap.remove(sessionId);
                }
            });

        }
    }

    @Override
    public void shutdown(String msg) {
        runFlag = false;
    }
}
